package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public void register(User user) {
        //检查邮箱是否存在
        User temp = userMapper.selectByEmailAndPassword(user.getEmail(), null);
        if (temp == null) {
            //设置默认的头像和背景图
            user.setHeadImgUrl("/img/user/head.jpg");
            user.setCoverImgUrl("/img/user/bg.jpeg");
            userMapper.insert(user);
        } else {
            throw new RuntimeException("该邮箱已被注册");
        }
    }

    public User login(String email, String password) {
        //根据用户的邮箱和密码查询
        User temp = userMapper.selectByEmailAndPassword(email, password);
        if (temp == null) {
            throw new RuntimeException("邮箱或密码错误");
        }
        return temp;
    }

    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        return new PageInfo(userMapper.queryForList(qo));
    }

    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
